﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using hedefgrup.reports.renault.definitions;
using hedefgrup.reports.renault;
using System.Text;
using hedefgrup.reports.renault.calculators;
using System.Globalization;
using System.Collections.Generic;

public partial class forms_dispersionResults_dispersionResults : reportPage
{
    private const string REPORT_HEADER_CELL_TEMPLATE = "<td width='100px' align='center' class='t_head' valign='center'>{0}</td>";
    private const string REPORT_ROW_TEMPLATE = "<tr><td>{0}</td><td>{1}</td>{2}</tr>";
    private const string REPORT_CELL_TEMPLATE = "<td align=right>{0}</td>";

    private const float LEFT = 91;
    private const float RIGHT = 849;
    private const float TOP = 52;
    private const float BOTTOM = 411;
    private const float WIDTH = RIGHT - LEFT;
    private const float HEIGHT = BOTTOM - TOP;

    private reportDefinition reportToRender;

    private void renderTableHeader()
    {
        StringBuilder htmlBuilder = new StringBuilder();
        foreach (reportRowDefinition row in reportToRender.rowDefinitions)
        {
            switch (row.getRowType())
            {
                case "base":
                    htmlBuilder.AppendFormat(REPORT_HEADER_CELL_TEMPLATE, "Baz");
                    break;
                case "percentage_of_option":
                case "formula_1":
                    htmlBuilder.AppendFormat(REPORT_HEADER_CELL_TEMPLATE, base.getDataCache().questionDefinitions[row.getQuestionToReport()].getName());
                    break;
                case "percentage_over_total_base":
                    htmlBuilder.AppendFormat(REPORT_HEADER_CELL_TEMPLATE, row.getAttributeByName("h"));
                    break;
            }
        }
        reportTableHeaderHtml.Text = htmlBuilder.ToString();
    }

    private static CultureInfo english = CultureInfo.GetCultureInfo("en-US");

    private static void appendMapDescriptor(dealerDefinition dealer, double xValue, double yValue, StringBuilder mapDescriptorBuilder)
    {
        int pointX = Convert.ToInt32(LEFT + WIDTH * (xValue / 100));
        int pointY = Convert.ToInt32(BOTTOM - HEIGHT * (yValue / 20));
        mapDescriptorBuilder.AppendFormat
        (
            "<area shape='rect' coords='{0},{1},{2},{3}' alt='{4} {5}\r\nMemnuniyet: %{6:0.0}\r\nArıza Dönüşü: %{7:0.0}'>",
            (pointX + 3),
            (pointY - 3),
            (pointX - 3),
            (pointY + 3),
            dealer.getCode(),
            dealer.getName(),
            xValue,
            yValue
        );
    }

    private bool dealerFitsCalculatorType(reportDealerInfo dealer)
    {
        return
        (
            base.calculationType == calculatorType.dealersAndSatellitesJoined
            &&
            (dealer.dealer.getAttributeByName("type") == "dealer" || dealer.dealer.getAttributeByName("type") == "branch")
        )
        ||
        (
            base.calculationType == calculatorType.connectedPoints
            &&
            dealer.dealer.getAttributeByName("type") == "connected_point"
            ||
            dealer.dealer.getCode() == "TR"
        )
        ||
        (
            base.calculationType == calculatorType.network1
            &&
            dealer.dealer.getAttributeByName("type") == "network1"
        )
        ||
        (
            base.calculationType == calculatorType.network2
            &&
            dealer.dealer.getAttributeByName("type") == "network2"
        )
        ||
        (
            base.calculationType == calculatorType.allnetworks
            &&
            dealer.dealer.getAttributeByName("type").StartsWith("network")
        );
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureUserIsLoggedIn();

        reportToRender = base.getDataCache().reportDefinitions["dispersion"];

        bool isGraphView = base.getString("v") == "graph";

        if (!isGraphView) this.renderTableHeader();

        StringBuilder htmlBuilder = new StringBuilder();

        reportDealerInfo[] generatedReport = base.getCalculator().generateReportDataForMultipleDealers(base.calculationType, base.getReportMonth(), base.getReportMonth() - base.cumulativeMonths + 1);

        double xValue = 0;
        double yValue = 0;
        StringBuilder xBuilder = new StringBuilder();
        StringBuilder yBuilder = new StringBuilder();
        StringBuilder mapDescriptorBuilder = new StringBuilder("<map id='mapDescriptor'>");

        foreach (reportDealerInfo dealer in generatedReport)
        {
            List<string> userDealerCodes = new List<string>(base.getUserDealerCodes());
            if (userDealerCodes.Count == 0 || userDealerCodes.Contains(dealer.dealer.getCode()))
            {
                if (dealerFitsCalculatorType(dealer))
                {
                    if (dealer.data.baseCount > 0)
                    {
                        StringBuilder cellBuilder = new StringBuilder();

                        foreach (reportRowDefinition row in reportToRender.rowDefinitions)
                        {
                            switch (row.getRowType())
                            {
                                case "base":
                                    if (!isGraphView) cellBuilder.AppendFormat(REPORT_CELL_TEMPLATE, dealer.data.baseCount);
                                    break;
                                case "percentage_of_option":
                                    xValue = 100 * dealer.data.questions[row.getQuestionToReport()].calculateOptionPercentage(Convert.ToInt32(row.getAttributeByName("o")));
                                    if (!isGraphView) cellBuilder.AppendFormat(REPORT_CELL_TEMPLATE, xValue);
                                    break;
                                case "percentage_over_total_base":
                                    double value = 0;
                                    string[] optionsToReport = row.getAttributeByName("o").Split(',');
                                    foreach (string optionToReportString in optionsToReport)
                                    {
                                        int optionToReport = Convert.ToInt32(optionToReportString);
                                        value += (double)dealer.data.questions[row.getQuestionToReport()].getOptionCount(optionToReport);
                                    }
                                    yValue = 100 * value / (double)dealer.data.baseCount;
                                    if (!isGraphView) cellBuilder.AppendFormat(REPORT_CELL_TEMPLATE, yValue);
                                    break;
                                case "formula_1":
                                    yValue = 100 * dealer.data.questions[row.getQuestionToReport()].calculateFormula1();
                                    if (!isGraphView) cellBuilder.AppendFormat(REPORT_CELL_TEMPLATE, yValue);
                                    break;
                            }
                        }
                        if (isGraphView)
                        {
                            appendMapDescriptor(dealer.dealer, xValue, yValue, mapDescriptorBuilder);
                            xBuilder.AppendFormat("{0}|", xValue.ToString("0.0", english));
                            yBuilder.AppendFormat("{0}|", yValue.ToString("0.0", english));
                        }
                        else
                        {
                            htmlBuilder.AppendFormat(REPORT_ROW_TEMPLATE, dealer.dealer.getCode(), dealer.dealer.getName(), cellBuilder);
                        }
                    }
                }
            }
        }

        if (!isGraphView)
        {
            reportTableHtml.Text = htmlBuilder.ToString();
        }
        else
        {
            tableViewDiv.Visible = false;
            mapDescriptorBuilder.Append("</map>");
            graphicsContainer.Text = string.Format
            (
                "<img src='/forms/common/graph2.aspx?m={0}&x={1}&y={2}' border='0' usemap='#mapDescriptor' />{3}",
                base.getReportMonth().dateValue,
                xBuilder,
                yBuilder,
                mapDescriptorBuilder
            );
        }


        base.RenderComplete();
        renderTime.Text = base.getElapsedRenderTime().ToString();

    }
}
